<?php

namespace App\Http\Controllers\API\Auth;

use Illuminate\Http\Request;
use App\Http\Controllers\API\APIController;

use Validator;
use VerificationCode;
use App\Models\API\User;
use Illuminate\Support\Facades\Hash;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

class AuthController extends APIController
{
	/**
     * 用户注册
     *
     * @return \Illuminate\Http\Response - json()
     */
	public function register(Request $request)
	{
        $v = Validator::make($request->all(), [
            'phone' => [
                'required',
                'regex:/^1[34578][0-9]{9}$/',
                'unique:users',
                'max:255'
            ],
            'password'  => 'required|min:6',
            'verification_code' => 'required'
        ]);

        if ($v->fails())
        {
            return response()->json($this->setJson(false, $v->errors()), 422);
        }

        if ($v->passes()) {
        	$phone = $request['phone'];
            $resouestCode = $request['verification_code'];
            $res = VerificationCode::check($phone, $resouestCode);

            if ($res['status']) {
            	$inputData = $request->all();
                $inputData['password'] = Hash::make($inputData['password']);
                User::create($inputData);
                $msg = '注册成功！';
            	return response()->json($this->setJson(true, $msg), 200);
            } else {
            	return response()->json($this->setJson($res['status'], $res['msg']), $res['code']);
            }
        }
	}

	/**
     * 用户认证
     *
     * @return \Illuminate\Http\Response - json()
     */
	public function login(Request $request)
    {
        $credentials = $request->only('phone', 'password');

        try {
            if (!$token = JWTAuth::attempt($credentials)) {
            	$msg = '手机号或者密码错误，请重新输入';
                return response()->json($this->setJson(false, $msg), 401);
            } else {
            	$user = User::where('phone', $request['phone'])->first();
		        $user_id = $user->id;
		        $phone = $user->phone;
		        $msg = [
			        'access_token' => $token, 
			        'user_id' => $user_id, 
			        'phone' => $phone
		        ];
		        return response()->json($this->setJson(true, $msg), 200);
            }
        } catch (JWTException $e) {
        	$msg = '认证失败！';
            return response()->json($this->setJson(false, $msg), 500);
        }
    }

    /**
     * 发送验证码
     *
     * @return \Illuminate\Http\Response - json()
     */
    public function getVerificationCode(Request $request)
    {
        $v = Validator::make($request->all(), [
            'phone' => [
                'required',
                'regex:/^1[34578][0-9]{9}$/'
            ]
        ]);

        if ($v->fails())
        {
            return response()->json($this->setJson(false, $v->errors()), 422);
        }

        // 手机号码正确时发送短信
        if ($v->passes())
        {   
            $phone = $request->get('phone');
            $res = VerificationCode::send($phone);
            return response()->json($this->setJson($res['status'], $res['msg']), $res['code']);
        }
    }

    /**
     * 修改密码前验证操作
     *
     * @return \Illuminate\Http\Response - json()
     */
    public function resetConfirm(Request $request)
    {
        $v = Validator::make($request->all(), [
            'phone' => [
                'required',
                'regex:/^1[34578][0-9]{9}$/',
                'exists:users',
                'max:255'
            ],
            'verification_code' => 'required'
        ]);

        if ($v->fails())
        {
            return response()->json($this->setJson(false, $v->errors()), 422);
        }

        if ($v->passes())
        {   
            $phone = $request->get('phone');
            $resouestCode = $request['verification_code'];
            $res = VerificationCode::check($phone, $resouestCode);

            if ($res['status']) {
                $msg = '验证成功';
            	return response()->json($this->setJson(true, $msg), 200);
            } else {
            	return response()->json($this->setJson($res['status'], $res['msg']), $res['code']);
            }
        }
    }

    /**
     * 修改密码
     *
     * @return \Illuminate\Http\Response - json()
     */
    public function reset(Request $request)
    {
        $v = Validator::make($request->all(), [
            'phone' => [
                'required',
                'regex:/^1[34578][0-9]{9}$/',
                'exists:users',
                'max:255'
            ],
            'password' => 'required|confirmed|min:6',
            'verification_code' => 'required'
        ]);

        if ($v->fails())
        {
            return response()->json($this->setJson(false, $v->errors()), 422);
        }

        if ($v->passes())
        {   
            $phone = $request->get('phone');
            $resouestCode = $request['verification_code'];

            $res = VerificationCode::check($phone, $resouestCode);

            if ($res['status']) {
            	$password = Hash::make($request['password']);
                $user = User::where('phone', $phone)->first();
                $user->password = $password;
                $user->save();
                $msg = '密码修改成功，请重新登录';
            	return response()->json($this->setJson(true, $msg), 200);
            } else {
            	return response()->json($this->setJson($res['status'], $res['msg']), $res['code']);
            }
        }
    }

    /**
     * 规范JSON
     *
     * @return Array
     */
    private function setJson($status, $msg)
    {
    	$res = [
    		'status' => $status,
    		'msg'    => $msg
    	];
    	return $res;
    }
}